﻿using System;
using System.Collections.Generic;

namespace DART.Detector.IRay
{
    /// <summary>
    /// IDictionary<string, object> 扩展方法
    /// </summary>
    public static class IDictionaryExtensions
    {
        /// <summary>
        /// 将 <paramref name="collection"/> 合并更新到当前数据
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="collection"></param>
        public static void Combine(this IDictionary<string, object> dic, IEnumerable<KeyValuePair<string, object>> collection)
        {
            if (collection != null)
                foreach (var item in collection)
                    dic[item.Key] = item.Value;
        }

        /// <summary>
        /// 获取指定 <paramref name="key"/> 的值并强制 <typeparamref name="T"/> 类型转换。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="InvalidCastException"></exception>
        public static T GetValue<T>(this IDictionary<string, object> dic, string key)
        {
            return (T)dic[key];
        }

        /// <summary>
        /// 获取指定 <paramref name="key"/> 的 <paramref name="value"/> 并强制 <typeparamref name="T"/> 类型转换。
        /// 如果 <paramref name="key"/> 不存在，返回 <paramref name="defaultValue"/>。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidCastException"></exception>
        public static T GetValue<T>(this IDictionary<string, object> dic, string key, T defaultValue)
        {
            return dic.TryGetValue(key, out var obj) ? (T)obj : defaultValue;
        }

        /// <summary>
        /// 尝试获取指定 <paramref name="key"/> 的 <paramref name="value"/>。
        /// 如果 <paramref name="key"/> 不存在，或 <typeparamref name="T"/> 类型不匹配，
        /// 返回 <see langword="false"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool TryGetValue<T>(this IDictionary<string, object> dic, string key, out T value)
        {
            var result = dic.TryGetValue(key, out var obj) && obj is T;
            value = result ? (T)obj : default;
            return result;
        }
    }

}